import { create } from 'zustand'
const MAX_TAGS_NUMBER = 20
const BASIC_ITEM = {
  key: '__index__',
  path: '/index',
  name: '首页',
  stopClose: true
}

export interface HistoryTag {
  key: string
  path: string
  name: string
  stopClose?: boolean
  updateTime?: number
}

export type State = {
  viewsTagsList: HistoryTag[],
  activeKey: HistoryTag['key']
}

type Action = {
  routerPushTags: (item: HistoryTag) => void
  routeDelTags: (key: string) => HistoryTag | undefined
  addTags: (item: HistoryTag) => void
  delTags: (key: string) => HistoryTag[]
  findTagsInList: (key: string) => number
  resetTagsList: () => void
  getItemByKey: (key: string) => HistoryTag | undefined
  getItemByIndex: (index: number) => HistoryTag | undefined
  toggleTags: (key: HistoryTag['key']) => void
}

const useHistoryTags = create<State & Action>((set, get) => ({
  viewsTagsList: [BASIC_ITEM],
  activeKey: '',
  routerPushTags (item) {
    const state = get()
    const isInTags = state.findTagsInList(item.key) >= 0
    if (isInTags) {
      state.toggleTags(item.key)
    } else {
      state.addTags(item)
      state.toggleTags(item.key)
    }
  },
  routeDelTags (key) {
    const state = get()
    const tagIndex = state.findTagsInList(key)
    if (tagIndex >= 0) { 
      state.delTags(key)
    }
    if(key === state.activeKey) {
      const item = state.getItemByIndex(tagIndex === 0 ? 0 : tagIndex - 1)
      state.toggleTags(item.key)
      return item
    }
  },
  addTags (item) {
    const state = get()
    if(state.viewsTagsList.length >= MAX_TAGS_NUMBER) {
      const [_, ...list] = state.viewsTagsList
      item.updateTime = Date.now()
      set(() => ({viewsTagsList: [...list, item]}))
    } else {
      set((state) => ({viewsTagsList: [...state.viewsTagsList, item]}))
    }
  },
  delTags (key) {
    const state = get()
    const tagIndex = state.findTagsInList(key)
    if (tagIndex >= 0) {
      const newList = state.viewsTagsList.slice(0, tagIndex).concat(state.viewsTagsList.slice(tagIndex + 1))
      set(() => ({viewsTagsList: newList}))
      return newList
    }
    return state.viewsTagsList
  },
  findTagsInList(key) {
    const state = get()
    return state.viewsTagsList.findIndex(e => e.key === key)
  },
  getItemByKey(key) {
    const state = get()
    return state.viewsTagsList.find(e => e.key === key)
  },
  getItemByIndex(index) {
    const state = get()
    return state.viewsTagsList[index] 
  },
  resetTagsList () {
    set(() => ({viewsTagsList: [BASIC_ITEM]}))
  },
  toggleTags (key) {
    set(() => ({activeKey: key}))
  }
}))


export default useHistoryTags